﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using iWare.Wms.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace iWare.Wms.Application
{
    /// <summary>
    /// 仓储管理看板服务
    /// </summary>
    [Route("api/TransportationBoard")]
    [ApiDescriptionSettings("看板", Name = "TransportationBoard", Order = 113)]

    public class TransportationBoardServer : IDynamicApiController, ITransient
    {
        private readonly IRepository<PurchaseOrder, MasterDbContextLocator> _purchaseOrderRep; //采购订单仓储
        private readonly IRepository<CollectDeliveryDetails, MasterDbContextLocator> _collectDeliveryRep; //收货单明细仓储
        private readonly IRepository<WareOrder, MasterDbContextLocator> _wareOrderRep; //单据仓储
        private readonly IRepository<WareLocation, MasterDbContextLocator> _wareLocationRep; //库位仓储
        private readonly IRepository<WareStock, MasterDbContextLocator> _wareStockRep; //库存仓储
        private readonly IRepository<v_order_status, MasterDbContextLocator> _orderStatust; //订单状态视图仓储
        private readonly IRepository<v_accessrecord, MasterDbContextLocator> _accessrecordRep; //出入库明细视图仓储

        #region 默认
        /// <summary>
        /// 默认
        /// </summary>
        /// <param name="purchaseOrderRep"></param>
        /// <param name="collectDeliveryRep"></param>
        /// <param name="wareOrderRep"></param>
        /// <param name="wareLocationRep"></param>
        /// <param name="wareStockRep"></param>
        /// <param name="orderStatust"></param>
        /// <param name="accessrecordRep"></param>
        public TransportationBoardServer(
             IRepository<PurchaseOrder, MasterDbContextLocator> purchaseOrderRep,
             IRepository<CollectDeliveryDetails, MasterDbContextLocator> collectDeliveryRep,
             IRepository<WareOrder, MasterDbContextLocator> wareOrderRep,
             IRepository<WareLocation, MasterDbContextLocator> wareLocationRep,
             IRepository<WareStock, MasterDbContextLocator> wareStockRep,
             IRepository<v_order_status, MasterDbContextLocator> orderStatust,
             IRepository<v_accessrecord, MasterDbContextLocator> accessrecordRep
         )
        {
            _purchaseOrderRep = purchaseOrderRep;
            _collectDeliveryRep = collectDeliveryRep;
            _wareOrderRep = wareOrderRep;
            _wareLocationRep = wareLocationRep;
            _wareStockRep = wareStockRep;
            _orderStatust = orderStatust;
            _accessrecordRep = accessrecordRep;
        }
        #endregion

        //当天0时0分0秒：
        DateTime start = Convert.ToDateTime(DateTime.Now.ToString("D").ToString());
        //当天23时59分59秒：
        DateTime end = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("D").ToString()).AddSeconds(-1);

        /// <summary>
        /// 库存库位单据模块
        /// </summary>
        /// <returns></returns>
        [HttpGet("WarehouseOperation")]
        [AllowAnonymous]
        public async Task<WarehouseOperationOutput> WarehouseOperation()
        {
            //查询库存总数
            var StockSumtd = new StockNumber
            {
                StockSum = await _wareStockRep.DetachedEntities.SumAsync(u => u.StockQuantity)
            };

            //查询库位状态
            var DocumentsList = new List<DocumentsNumberOutput>();

            //查询单据数量
            var BillNumbertd = new BillNumber
            {
                ReceiptDoc = await _purchaseOrderRep.DetachedEntities.Where(e => e.Status == PurchaseStatusEnum.NotProgress).CountAsync(),
                OutboundOrder = await _wareOrderRep.DetachedEntities.Where(e => e.OrderStatus == IssueStausEnum.NOTZHIXING).CountAsync(),
                CountSheet = await _purchaseOrderRep.DetachedEntities.Where(e => e.CreatedTime > start && e.CreatedTime < end).CountAsync(),
            };

            //库存库位单据
            var WarehouseOperationtion = new WarehouseOperationOutput
            {
                StockNumbertion = StockSumtd,
                LocationNumbertion = Location(),
                BillNumbertion = BillNumbertd
            };

            return WarehouseOperationtion;
        }

        /// <summary>
        /// 库位数据赋值
        /// </summary>
        /// <returns></returns>
        [HttpGet("LocationNumberdt")]
        [AllowAnonymous]
        public List<LocationNumber> Location()
        {
            var IibraryNumber = _wareLocationRep.DetachedEntities.ToList();

            var LocationList = new List<LocationNumber>();
            for (int i = 0; i < 6; i++)
            {
                var Locationdt = new LocationNumber();
                if (i == 0)
                {
                    Locationdt.IibraryNumber = IibraryNumber.Where(e => e.IsLock == YesOrNot.N && e.IsEmptyContainer == YesOrNot.N && e.LocationStatus == LocationStatusEnum.cunhuo).Count();
                    Locationdt.IibraryState = "实盘在库";
                    Locationdt.IibraryColour = "#188FE4";
                }
                if (i == 1)
                {
                    Locationdt.IibraryNumber = IibraryNumber.Where(e => e.IsLock == YesOrNot.N && e.IsEmptyContainer == YesOrNot.Y && e.LocationStatus == LocationStatusEnum.cunhuo).Count();
                    Locationdt.IibraryState = "空盘在库";
                    Locationdt.IibraryColour = "#56E014";
                }
                if (i == 2)
                {
                    Locationdt.IibraryNumber = IibraryNumber.Where(e => e.IsLock == YesOrNot.N && e.IsEmptyContainer == YesOrNot.N && e.LocationStatus == LocationStatusEnum.kongxian).Count();
                    Locationdt.IibraryState = "库位空闲";
                    Locationdt.IibraryColour = "#DDD716";
                }
                if (i == 3)
                {
                    Locationdt.IibraryNumber = IibraryNumber.Where(e => e.IsLock == YesOrNot.Y).Count();
                    Locationdt.IibraryState = "库位占用";
                    Locationdt.IibraryColour = "#F01845";
                }
                if (i == 4)
                {
                    Locationdt.IibraryNumber = IibraryNumber.Where(e => e.IsLock == YesOrNot.N && e.IsEmptyContainer == YesOrNot.N && e.LocationStatus == LocationStatusEnum.daichu).Count();
                    Locationdt.IibraryState = "库位待入";
                    Locationdt.IibraryColour = "#18B3F0";
                }
                if (i == 5)
                {
                    Locationdt.IibraryNumber = IibraryNumber.Where(e => e.IsLock == YesOrNot.N && e.IsEmptyContainer == YesOrNot.N && e.LocationStatus == LocationStatusEnum.cunhuo).Count();
                    Locationdt.IibraryState = "库位待出";
                    Locationdt.IibraryColour = "#71B62A";
                }
                LocationList.Add(Locationdt);
            }

            return LocationList;
        }

        /// <summary>
        /// 出入库数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("WarehousingIssue")]
        [AllowAnonymous]
        public async Task<List<WarehousingIssueOutput>> WarehousingIssue()
        {
            int days = -30;

            var Accessrecord = await _accessrecordRep.Where(p => p.TaskCreatedTime >= DateTime.Now.Date.AddDays(days)).OrderByDescending(n => n.TaskCreatedTime).ToListAsync();
            
            var WarehousingList = new List<WarehousingIssueOutput>();
            for (int i = 0; i >= days; i--)
            {
                var starttime = DateTime.Now.Date.AddDays(i);
                var endtime = DateTime.Now.Date.AddDays(i + 1);
                var AccessrecordList = Accessrecord.Where(p => p.TaskCreatedTime >= starttime && p.TaskCreatedTime <= endtime).ToList();
                var model = new WarehousingIssueOutput()
                {
                    WarehousingNumber = AccessrecordList.Where(e => e.TaskType == TaskType.In).Sum(e => e.BindQuantity),
                    IssueNumber = AccessrecordList.Where(e => e.TaskType == TaskType.Out).Sum(e => e.BindQuantity),
                    InventoryNumber = AccessrecordList.Where(e => e.TaskType == TaskType.In).Sum(e => e.BindQuantity),
                    dateStr = starttime.ToString("MM/dd")
                };
                WarehousingList.Add(model);
            }

            return WarehousingList;
        }

        /// <summary>
        /// 单据明细数
        /// </summary>
        /// <returns></returns>
        [HttpGet("DocumentsNumber")]
        [AllowAnonymous]
        public async Task<List<DocumentsNumberOutput>> DocumentsNumber()
        {
            int days = -30;

            var ReceiptDoced = await _purchaseOrderRep.Where(p => p.CreatedTime >= DateTime.Now.Date.AddDays(days) && (p.Status == PurchaseStatusEnum.Progress || p.Status == PurchaseStatusEnum.Complete))
                .OrderByDescending(n => n.CreatedTime).ToListAsync();

            var OutboundOrderde = await _wareOrderRep.Where(p => p.CreatedTime >= DateTime.Now.Date.AddDays(days) && (p.OrderStatus == IssueStausEnum.ZHIXINGZHONG || p.OrderStatus == IssueStausEnum.WANCHENG))
                .OrderByDescending(n => n.CreatedTime).ToListAsync();
            var DocumentsList = new List<DocumentsNumberOutput>();

            for (int i = 0; i >= days; i--)
            {
                var starttime = DateTime.Now.Date.AddDays(i);
                var endtime = DateTime.Now.Date.AddDays(i + 1);
                var ReceiptDocList = ReceiptDoced.Where(p => p.CreatedTime >= starttime && p.CreatedTime <= endtime).Count();
                var OutboundOrderList = OutboundOrderde.Where(p => p.CreatedTime >= starttime && p.CreatedTime <= endtime).Count();
                var model = new DocumentsNumberOutput()
                {
                    ReceiptDoc = ReceiptDocList,
                    OutboundOrder = OutboundOrderList,
                    dateStr = starttime.ToString("MM/dd")
                };
                DocumentsList.Add(model);
            }

            return DocumentsList;
        }

        /// <summary>
        /// 百分比模型详情
        /// </summary>
        /// <returns></returns>
        [HttpGet("Percentage")]
        [AllowAnonymous]
        public async Task<PercentageOutput> Percentage()
        {
            //查询出入库单据详情
            var ReceiptDoced = await _purchaseOrderRep.DetachedEntities.ToListAsync();

            var OutboundOrderde = await _wareOrderRep.DetachedEntities.ToListAsync();

            var PercentageBilldt = new PercentageBill
            {
                IssueSum = ReceiptDoced.Where(e => e.Status != PurchaseStatusEnum.Delete).Count(),
                IssueImplement = ReceiptDoced.Where(e => e.Status == PurchaseStatusEnum.Complete || e.Status == PurchaseStatusEnum.Progress).Count(),
                IssueUnexecuted = ReceiptDoced.Where(e => e.Status == PurchaseStatusEnum.NotProgress).Count(),
                WarehousingSum = OutboundOrderde.Count(),
                WarehousingImplement = OutboundOrderde.Where(e => e.OrderStatus == IssueStausEnum.WANCHENG || e.OrderStatus == IssueStausEnum.ZHIXINGZHONG).Count(),
                WarehousingUnexecuted = OutboundOrderde.Where(e => e.OrderStatus == IssueStausEnum.NOTZHIXING).Count(),
                InventorySum = OutboundOrderde.Count(),
                InventoryImplement = OutboundOrderde.Where(e => e.OrderStatus == IssueStausEnum.WANCHENG || e.OrderStatus == IssueStausEnum.ZHIXINGZHONG).Count(),
                InventoryUnexecuted = OutboundOrderde.Where(e => e.OrderStatus == IssueStausEnum.NOTZHIXING).Count(),
            };

            //不良明细赋值
            var CollectDelivery = await _collectDeliveryRep.Where(e => e.IsQuality == YesOrNot.Y).ToListAsync();
            var QualityList = new List<QualityTesting>();
            for (int i = 0; i < 3; i++)
            {
                var Qualitydt = new QualityTesting();
                if (i == 0)
                {
                    Qualitydt.QualityNumber = CollectDelivery.Where(e => e.QualityResult == QualityEnum.FanXiu).Count();
                    Qualitydt.QualityName = "返修";
                    Qualitydt.QualityColour = "#188FE4";
                }
                if (i == 1)
                {
                    Qualitydt.QualityNumber = CollectDelivery.Where(e => e.QualityResult == QualityEnum.BaoFei).Count();
                    Qualitydt.QualityName = "报废";
                    Qualitydt.QualityColour = "#56E014";
                }
                if (i == 2)
                {
                    Qualitydt.QualityNumber = CollectDelivery.Where(e => e.QualityResult == QualityEnum.TuiHuo).Count();
                    Qualitydt.QualityName = "退货";
                    Qualitydt.QualityColour = "#DDD716";
                }
                QualityList.Add(Qualitydt);
            }

            //百分比模型赋值
            var Percentagetd = new PercentageOutput
            {
                percentageBilltion = PercentageBilldt,
                LocationNumbertion = Location(),
                QualityTestingtion = QualityList
            };

            return Percentagetd;
        }

        /// <summary>
        /// 订单状态
        /// </summary>
        /// <returns></returns>
        [HttpGet("OrderStatusdt")]
        [AllowAnonymous]
        public async Task<List<OrderStatusOutput>> OrderStatusdt()
        {
            var list = await _orderStatust.DetachedEntities.ToListAsync();

            var OrderStatus = new List<OrderStatusOutput>();
            foreach (var item in list)
            {
                var Orderdt = new OrderStatusOutput
                {
                    OrderNo = item.OrderNo,
                    OrderType = item.OrderType == 1 ? "采购入库" : (item.OrderType == 2 ? "销售出库" : "移库"),
                    OrderStatus = item.OrderType == 1 ? "入库中" : (item.OrderType == 2 ? "待出库" : "移库中"),
                };
                OrderStatus.Add(Orderdt);
            }

            return OrderStatus;
        }
    }
}
